<?php
namespace app\admin\service;

use think\Request;
use app\admin\model\AuthGroup;
use app\admin\model\AuthRule;
use think\db\Query;

/**
 * 用户权限判断类
 */
class AuthService
{
    public function __construct(private Request $request, private int $admin_id)
    {
        
    }

    /**
     * 获取当前路由
     */
    public function getCurrentNode(): string
    {
        $node = request()->controller() . '/' . request()->action();
        return $node;
    }

    /**
     * 获取权限节点ID
     */
    private function getRuleIds(): array
    {
        $roles = AuthGroup::hasWhere('AuthGroupAccess', function(Query $query) {
            $query->where('uid', '=', $this->admin_id);
        })->field('AuthGroup.rules')->select();

        $ids = [];
        foreach($roles as $role) {
            $ids = array_merge($ids, explode(',', trim($role->rules, ',')));
        }
        
        $ids = array_unique($ids);
        return $ids;
    }

    /**
     * 判断是否有权限
     */
    public function check(string $node)
    {
        // 获取用户权限
        $rulesIds = $this->getRuleIds();

        // * 表示全部权限
        if (in_array('*', $rulesIds)) {
            return true;
        }

        // 获取节点对应的ID
        $nodeId = AuthRule::where('name', '=', $node)->value('id');
        if ($nodeId && in_array($nodeId, $rulesIds)) {
            return true;
        }

        return false;
    }
}